<script setup>
  import { ref, inject } from 'vue'
  import { useI18n } from 'vue-i18n'

  const { t } = useI18n()
  const emit = defineEmits(['reLoad', 'getMore'])

  const props = defineProps({
    nodata: Boolean,
    isEnd: Boolean,
    lokcTopRefresh: {
      type: Boolean,
      default: false
    }
  })

  console.log(props)

  const refresh = ref()

  // 节流设置
  const lock = ref(false)

  // 设置高度
  const topDistanceY = inject('topDistanceY', 0)
  const bottomDistanceY = inject('bottomDistanceY', 0)

  // 动起点的坐标
  const startY = ref(0)

  // 滑动距离
  const distanceY = ref(0)

  // 提示
  const topLoadTitle = ref('')
  const bottomLoadTitle = ref('')

  const refreshTip1 = t('config.refreshTip1')
  const refreshTip2 = t('config.refreshTip2')
  const refreshTip3 = t('config.refreshTip3')
  const refreshTip4 = t('config.refreshTip4')

  topLoadTitle.value = refreshTip1
  bottomLoadTitle.value = refreshTip2
  // const scale = ref(0)

  const rotate = ref(false)

  const touchOnTop = (e) => {
    if (lock.value) return
    //滑动起点的坐标
    startY.value = e.targetTouches[0].pageY
  }

  const touchOnTopMove = (e) => {
    if (lock.value) return

    let touch = e.targetTouches[0]
    let touchMove = touch.pageY - startY.value
    // console.log((Math.abs(touchMove)*2)/100)

    if (Math.abs(touchMove) < 50) {
      // scale.value = (touchMove*2)/100
    } else {
      topLoadTitle.value = refreshTip3
      bottomLoadTitle.value = refreshTip3
      // scale.value = 1
    }

    //手势滑动时，手势坐标不断变化，取最后一点的坐标为最终的终点坐标
    console.log(refresh.value.scrollTop)
    console.log(refresh.value.clientHeight)
    console.log(refresh.value.scrollHeight)
    if (touchMove > 0) {
      console.log('startY:', startY.value)
      if (refresh.value.scrollTop == 0 && !props.lokcTopRefresh) {
        distanceY.value = touchMove
      } else {
        startY.value = touch.pageY
      }
    } else if (touchMove < 0) {
      console.log('startY:', startY.value)
      if (refresh.value.scrollTop + refresh.value.clientHeight + 100 > refresh.value.scrollHeight) {
        console.log('in End')
        // if(touchMove < 0) {
        // distanceY.value = touchMove
        // }
        if (!props.nodata || !props.isEnd) {
          getMore()
        }
      }
      // else {
      //   startY.value = touch.pageY
      // }
    }

    console.log('distanceY:' + distanceY.value)
  }

  const touchOnTopEnd = () => {
    if (lock.value) return
    //移动端设备的屏幕宽度
    //判断是否滑动了，而不是屏幕上单击了
    if (startY.value != Math.abs(distanceY.value)) {
      //在滑动的距离超过屏幕高度的50时，做某种操作
      if (Math.abs(distanceY.value) > 50) {
        distanceY.value < 0 ? getMore() : reLoad()
      } else {
        backEnd(0, () => {})
      }
    }
  }

  const countDown = ref(0)
  const countDistanceY = ref(0)

  const reLoad = () => {
    lock.value = true
    backEnd(50, () => {
      emit('reLoad')
    })
  }

  const getMore = () => {
    if (props.nodata || props.isEnd) return
    lock.value = true
    // backEnd(-50,() => {
    //   emit("getMore");
    // })
    emit('getMore')
  }

  const loadEnd = () => {
    backEnd(0, () => {})
    rotate.value = false
    lock.value = false
  }

  const backEnd = (e, callBack) => {
    if (Math.abs(e) == 50) {
      rotate.value = true
      topLoadTitle.value = refreshTip4
      bottomLoadTitle.value = refreshTip4
    } else {
      topLoadTitle.value = refreshTip1
      bottomLoadTitle.value = refreshTip2
    }
    countDistanceY.value = (distanceY.value - e) / 30
    let timer = setInterval(() => {
      if (countDown.value == 30) {
        countDown.value = 0
        countDistanceY.value = 0
        distanceY.value = e
        callBack()
        clearInterval(timer)
      } else {
        distanceY.value = distanceY.value - countDistanceY.value
        countDown.value++
      }
    }, 10)
  }

  // const debounce = (callback, delay) => {
  //   var t = null;
  //   return function () {
  //     clearTimeout(t);
  //     t = setTimeout(callback, delay);
  //   };
  // };

  // const createScroll = () => {
  //   // var timeout  = null
  //   window.addEventListener('scroll', debounce(() => loadGetMore(),500), true);
  // }
  // const removeScroll = () => {
  //   window.removeEventListener("scroll", loadGetMore(), true);
  // }

  // const isUpOrDown = ref(0)
  // const loadGetMore = () => {
  // console.log(refresh.value.scrollTop)
  // if(refresh.value.scrollTop + refresh.value.clientHeight > isUpOrDown.value) {
  //   if((refresh.value.scrollTop + refresh.value.clientHeight + 100) > refresh.value.scrollHeight) {
  //     lock.value = true
  //     console.log('addEventListener in End')
  //     if(!props.nodata || !props.isEnd) {
  //       getMore()
  //     }else {
  //       lock.value = false
  //     }
  //   }
  // }
  // isUpOrDown.value = refresh.value.scrollTop + refresh.value.clientHeight
  // }
  //使用 <script setup> 的组件是默认关闭的，也即通过模板 ref 或者 $parent 链获取到的组件的公开实例，不会暴露任何在 <script setup> 中声明的绑定。
  //https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineexpose
  defineExpose({
    loadEnd
    // createScroll,
    // removeScroll
  })
</script>
<template>
  <div style="position: relative; overflow: hidden">
    <div class="load flex-center-center" :style="{ top: distanceY - 50 + topDistanceY + 'px' }">
      <img class="icon" :class="{ rotate: rotate }" src="@/assets/img/refresh/refresh.png" alt="" />
      <p>{{ topLoadTitle }}</p>
    </div>
    <div
      ref="refresh"
      class="refresh"
      :style="{ transform: 'translateY(' + distanceY + 'px)' }"
      @touchstart="touchOnTop($event)"
      @touchmove="touchOnTopMove($event)"
      @touchend="touchOnTopEnd"
    >
      <div v-if="nodata" class="nodata flex-center-center">
        <img class="icon" src="@/assets/img/refresh/nodata.png" alt="" />
        {{ t('config.nodata') }}
      </div>
      <slot></slot>
      <div v-if="!nodata && isEnd" class="isEnd flex-center-center">
        <img class="icon" src="@/assets/img/refresh/end.png" alt="" />
        {{ t('config.nomore') }}
      </div>
    </div>
    <div
      v-if="distanceY < 0"
      class="load_bottom flex-center-center"
      :style="{ bottom: Math.abs(distanceY) - 50 + bottomDistanceY + 'px' }"
    >
      <img class="icon" :class="{ rotate: rotate }" src="@/assets/img/refresh/refresh.png" alt="" />
      <p>{{ bottomLoadTitle }}</p>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  .load {
    position: absolute;
    width: 100%;
    top: -50px;
    height: 50px;
    transform: scale(1);
    .icon {
      width: 20px;
      margin-right: 10px;
      transform: rotate(0deg);
      &.rotate {
        animation: rotate 1s ease infinite;
      }
    }
  }
  .load_bottom {
    position: fixed;
    width: 100%;
    bottom: -50px;
    height: 50px;
    transform: scale(1);
    .icon {
      width: 20px;
      margin-right: 10px;
      transform: rotate(0deg);
      &.rotate {
        animation: rotate 1s ease infinite;
      }
    }
  }
  .refresh {
    height: 100%;
    overflow: auto;
  }
  .nodata {
    width: 100%;
    height: 100%;
    text-align: center;
    flex-direction: column;
    font-size: 18px;
    line-height: 2;
    color: #969799;
    .icon {
      width: 150px;
    }
  }
  .isEnd {
    height: 40px;
    .icon {
      width: 30px;
      margin-right: 10px;
    }
  }
  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
</style>
